import { Button, Table, type TableColumnsType } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import type * as React from 'react';
import AddTradeModal from './AddTradeModal';
import AdminTradeModal from './AdminTradeModal';

interface TradeDataType {
  key: React.Key;
  tradeID: number;
  cardID: string;
  tradeDate: string;
  tradeType: '存入' | '支取' | '转账';
  tradeMoney: number;
  current_balance: number;
  remark?: string;
}

const columns: TableColumnsType<TradeDataType> = [
  {
    title: '交易ID',
    dataIndex: 'tradeID',
    sorter: (a, b) => a.tradeID - b.tradeID,
  },
  {
    title: '卡号',
    dataIndex: 'cardID',
  },
  {
    title: '交易日期',
    dataIndex: 'tradeDate',
    sorter: (a, b) =>
      new Date(a.tradeDate).getTime() - new Date(b.tradeDate).getTime(),
  },
  {
    title: '交易类型',
    dataIndex: 'tradeType',
    filters: [
      { text: '存入', value: '存入' },
      { text: '支取', value: '支取' },
      { text: '转账', value: '转账' },
    ],
    onFilter: (value, record) => record.tradeType === value,
  },
  {
    title: '交易金额',
    dataIndex: 'tradeMoney',
    sorter: (a, b) => a.tradeMoney - b.tradeMoney,
  },
  {
    title: '余额',
    dataIndex: 'current_balance',
    sorter: (a, b) => a.current_balance - b.current_balance,
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
];

function AdminTrade() {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [selectedTrade, setSelectedTrade] = useState<TradeDataType | null>(
    null,
  );
  const [trades, setTrades] = useState<TradeDataType[]>([]);

  const fetchTrades = useCallback(() => {
    fetch('http://localhost:8000/trades/')
      .then((response) => response.json())
      .then((data) => {
        const formattedData = data.map((trade: any) => ({
          key: trade.tradeID,
          tradeID: trade.tradeID,
          cardID: trade.cardID,
          tradeDate: new Date(trade.tradeDate).toLocaleString(),
          tradeType: trade.tradeType,
          tradeMoney: trade.tradeMoney,
          current_balance: trade.current_balance,
          remark: trade.remark,
        }));
        setTrades(formattedData);
      });
  }, []);

  useEffect(() => {
    fetchTrades();
  }, [fetchTrades]);

  const handleRowClick = (record: TradeDataType) => {
    setSelectedTrade(record);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setSelectedTrade(null);
  };

  const handleOperationSuccess = () => {
    fetchTrades();
    setIsModalVisible(false);
    setIsAddModalVisible(false);
  };

  return (
    <>
      <Button
        type="primary"
        style={{ marginBottom: 16 }}
        onClick={() => setIsAddModalVisible(true)}
      >
        新建记录
      </Button>
      <Table<TradeDataType>
        columns={columns}
        dataSource={trades}
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
      />
      {selectedTrade && (
        <AdminTradeModal
          visible={isModalVisible}
          onCancel={handleCancel}
          trade={selectedTrade}
          onSuccess={handleOperationSuccess}
        />
      )}
      <AddTradeModal
        visible={isAddModalVisible}
        onCancel={() => setIsAddModalVisible(false)}
        onSuccess={handleOperationSuccess}
      />
    </>
  );
}

export default AdminTrade;
